﻿using System;
using System.Data;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;


namespace FTP_progress
{
    class Excelhelper
    {
        public DataSet ExcelToDataSet(string fileName)
        {
            return ExcelToDataSet(fileName, true);
        }

        public DataSet ExcelToDataSet(string fileName, bool firstRowAsHeader)
        {
            int sheetCount = 0;
            return ExcelToDataSet(fileName, firstRowAsHeader, out sheetCount);
        }

        public DataSet ExcelToDataSet(string fileName, bool firstRowAsHeader, out int sheetCount)
        {
            DataSet ds = new DataSet();
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //FileShare.ReadWrite加上这个参数，即便文件被其他应用打开，也照常运行
            IWorkbook workbook = WorkbookFactory.Create(fileStream);
            IFormulaEvaluator evaluator = WorkbookFactory.CreateFormulaEvaluator(workbook);

            sheetCount = workbook.NumberOfSheets;//读取sheet的数量

            for (int i = 0; i < sheetCount; ++i)
            {
                ISheet sheet = workbook.GetSheetAt(i);
                DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
                ds.Tables.Add(dt);
            }
            return ds;


        }

        public DataTable ExcelToDataTable(string fileName, string sheetName)
        {
            return ExcelToDataTable(fileName, sheetName, true);
        }

        public DataTable ExcelToDataTable(string fileName, string sheetName, bool firstRowAsHeader)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = WorkbookFactory.Create(fileStream);

                IFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);

                ISheet sheet = workbook.GetSheet(sheetName);

                return ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
            }
        }

        private DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator, bool firstRowAsHeader)
        {
            if (firstRowAsHeader)
            {
                return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
            }
            else
            {
                return ExcelToDataTable(sheet, evaluator);
            }
        }

        private DataTable ExcelToDataTableFirstRowAsHeader(ISheet sheet, IFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                IRow firstRow = sheet.GetRow(0);
                int cellCount = GetCellCount(sheet);

                for (int i = 0; i < cellCount; i++)
                {
                    if (firstRow.GetCell(i) != null)
                    {
                        dt.Columns.Add(firstRow.GetCell(i).StringCellValue ?? string.Format("F{0}", i + 1), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);

                    if (row == null) continue;
                    bool isEmptyRow = true;
                    foreach (ICell cell in row.Cells)
                    {
                        if (cell != null && cell.CellType != CellType.Blank)
                        {
                            isEmptyRow = false;
                            break;
                        }
                    }
                    if (isEmptyRow) continue;


                    DataRow dr = dt.NewRow();
                    FillDataRowByRow(row, evaluator, ref dr);
                    dt.Rows.Add(dr);
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }

        private DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                if (sheet.LastRowNum != 0)
                {
                    int cellCount = GetCellCount(sheet);

                    for (int i = 0; i < cellCount; i++)
                    {
                        dt.Columns.Add(string.Format("F{0}", i), typeof(string));
                    }

                    for (int i = 0; i < sheet.FirstRowNum; ++i)
                    {
                        DataRow dr = dt.NewRow();
                        dt.Rows.Add(dr);
                    }

                    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);


                        if (row == null) continue;
                        bool isEmptyRow = true;
                        foreach (ICell cell in row.Cells)
                        {
                            if (cell!=null && cell.CellType!=CellType.Blank)
                            {
                                isEmptyRow = false;
                                break;
                            }
                        }
                        if (isEmptyRow) continue;
                        


                        
                        DataRow dr = dt.NewRow();
                        FillDataRowByRow(row, evaluator, ref dr);
                        dt.Rows.Add(dr);
                    }
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }

        /// <summary>
        /// 填充数据
        /// </summary>
        /// <param name="row"></param>
        /// <param name="evaluator"></param>
        /// <param name="dr"></param>
        private void FillDataRowByRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr)
        {
            if (row != null)
            {
                for (int j = 0; j < dr.Table.Columns.Count; j++)
                {
                    ICell cell = row.GetCell(j);

                    if (cell != null)
                    {
                        switch (cell.CellType)
                        //  switch( cell.CachedFormulaResultType)


                        {
                            case CellType.Blank:
                                {
                                    dr[j] = DBNull.Value;
                                    break;
                                }
                            case CellType.Boolean:
                                {
                                    dr[j] = cell.BooleanCellValue;
                                    break;
                                }
                            case CellType.Numeric:
                                {
                                    if (DateUtil.IsCellDateFormatted(cell))
                                    {
                                        dr[j] = cell.DateCellValue;
                                    }
                                    else
                                    {
                                        dr[j] = cell.NumericCellValue;
                                    }
                                    break;
                                }
                            case CellType.String:
                                {
                                    dr[j] = cell.StringCellValue;
                                    break;
                                }
                            case CellType.Error:
                                {
                                    dr[j] = cell.ErrorCellValue;
                                    break;
                                }
                            case CellType.Formula:
                                {

                                    //cell = evaluator.EvaluateInCell(cell) as HSSFCell;
                                    //dr[j] = cell.ToString();


                                    dr[j] = cell.NumericCellValue;

                                    break;
                                }
                            default:
                                throw new NotSupportedException(string.Format("Unsupported format type:{0}", cell.CellType));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取单元格
        /// </summary>
        /// <param name="sheet"></param>
        /// <returns></returns>
        private static int GetCellCount(ISheet sheet)
        {
            int firstRowNum = sheet.FirstRowNum;

            int cellCount = 0;

            for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
            {
                IRow row = sheet.GetRow(i);

                if (row != null && row.LastCellNum > cellCount)
                {
                    cellCount = row.LastCellNum;
                }
            }
            return cellCount;
        }
    }
}
